import axios, { AxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus';
import { getToken } from '@/utils/auth';

export const RespCodeOk = 200;
// *接口api返回结果约束不含data
export interface Result<T = any> {
  code: number;
  message?: string;
  data: T;
  [key: string]: unknown;
}

let requestFailNum = 0;
const service = axios.create({
  baseURL: '/automation/boltdog/openapi/v2',
  timeout: 5000000,
});

service.interceptors.request.use(
  (config) => {
    if (getToken()) {
      config.headers['authToken'] = getToken();
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response) => {
    if (response.data && response.data.code == '401') {
      // 给基座应用发送数据，退出登录
      // window.microApp.setGlobalData({ code: '401' })
      if (requestFailNum < 1) {
        requestFailNum = requestFailNum + 1;
        window.microApp.setGlobalData({ code: '401' });
      }
    } else if (response.data.msg === 'session 超时') {
      requestFailNum = requestFailNum + 1;
      window.microApp.setGlobalData({ code: '401' });
    } else {
      if (requestFailNum > 0) requestFailNum = 0;
      return response;
    }
    return response;
  },
  (error) => {
    if (error.status === 401) {
      // 给基座应用发送数据，退出登录
      window.microApp.setGlobalData({ code: '401' });
    }
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  },
);

// 封装通用请求方法
export function request<T = any>(config: AxiosRequestConfig): Promise<Result<T>> {
  return service.request(config);
}

export default service;
